<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<!-- react核心库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<!-- 支持react操作DOM -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<!-- 引入Babel，用于将JSX转换为JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<!-- prop-types -->
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

    <style>
        .list{
            width: 200;
            height: 150px;
            background-color: #a9a8dd;
            overflow: auto;
        }
        .news{
            height: 30px;
        }
    </style>

</head>
<body>
<div id="test"></div>
<script type="text/babel"> 
    //生命周期回调函数，生命周期钩子函数 
    class NewsList extends React.Component{
        state = {newsArr:[]}

        componentDidMount(){
            setInterval(()=>{
                //获取原状态
                const {newsArr} = this.state
                //模拟一条新闻
                const news = '新闻' + (newsArr.length+1)
                //更新状态,在这个newsArr中，开始的新生成的新闻，后面接的是以前的新闻
                this.setState({newsArr:[news,...newsArr]})
            },1000)
        }

        getSnapshotBeforeUpdate(){
            console.log('getSnapShotBebforeUpdate')
            return this.refs.list.scrollHeight;
        }

        componentDidUpdate(prevProps,prevState,height){
            console.log('componentDidUpdate')
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }

        render(){
            return(
                <div className="list" ref="list">
                    {
                        this.state.newsArr.map((item, index)=>{
                            return <div key={index} className="news">{item}</div>
                        })
                    }
                </div>
            )
        }
    }
    ReactDOM.render(<NewsList/>,document.getElementById('test'))
</script>
</body>
</html>